package com.dengyuanke.wx.controller;


import com.dengyuanke.wx.service.WeixinService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

/**
 * Created by FirenzesEagle on 2016/5/30 0030.
 * Email:liumingbo2008@gmail.com
 */
@RestController
@ApiIgnore
public class CoreController{

    @Autowired
    private WeixinService wxService;

    /**
     * 通过openid获得基本用户信息
     * 详情请见: http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html
     *
     * @param openid   openid
     * @param lang     zh_CN, zh_TW, en
     */
    @RequestMapping(value = "/getUserInfo")
    public WxMpUser getUserInfo(@RequestParam(value = "openid") String openid, @RequestParam(value = "lang") String lang) throws Exception{
        return this.wxService.getUserService().userInfo(openid, lang);
    }

    /**
     * 通过code获得基本用户信息
     * 详情请见: http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html
     *
     * @param code     code
     * @param lang     zh_CN, zh_TW, en
     */
    @RequestMapping(value = "/getOAuth2UserInfo")
    public WxMpUser getOAuth2UserInfo( @RequestParam(value = "code") String code, @RequestParam(value = "lang",required = false) String lang) throws Exception{
        WxMpOAuth2AccessToken accessToken= this.wxService.oauth2getAccessToken(code);
        return this.wxService.getUserService().userInfo(accessToken.getOpenId(), lang);
    }

    /**
     * 用code换取oauth2的openid
     * 详情请见: http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html
     * @param code     code
     */
    @RequestMapping(value = "/getOpenid")
    public String getOpenid(@RequestParam(value = "code") String code) throws Exception{
        WxMpOAuth2AccessToken accessToken = this.wxService.oauth2getAccessToken(code);
         return  accessToken.getOpenId();
    }

}
